import React from 'react';
import "@/style/Gobang.css"
import Checkerboard from './Checkerboard'
import Message from '../MessageSystem/Message'
import Chat from '../MessageSystem/Chat'
const coordinate = {
  goX:['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'],
  goY:[15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]
}
class Gobang extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(225).fill(null)
      }],
      blackIsNext: true,
      over: false,
      blackWin: Array(props.count).fill(0),  // 黑棋赢法次数记录
      whiteWin: Array(props.count).fill(0),  // 白棋赢法次数记录
      currentPosition: -1,
      location: -1,
      role: 'wry'  // wry、ngwt、sgye 闻人语、南宫问天、上官伊儿
    }
    this.dealClick = this.dealClick.bind(this)
    this.calculateWinner = this.calculateWinner.bind(this)
    this.setBang = this.setBang.bind(this)
    this.computerAI = this.computerAI.bind(this)
  }

  // 点击事件，逐层传递
  dealClick(location,i,x,y){
    console.log(this.state.blackIsNext?"黑方落子":"白方落子");
    this.setBang(location,i,x,y) // 黑棋先行，电脑在其之后执行
    setTimeout(() => {
      this.computerAI()
    }, 0);
  }

  // 落子函数集成
  setBang(location,i,x,y) {
    if(this.state.over) {
      return false
    }
    const history = this.state.history
    const current = history[history.length-1];
    const squares = current.squares.slice();
    squares[i] = this.state.blackIsNext ? 1 : 2;  // 1为黑，2为白（注意不要设置0为黑或白）
    this.setState((state, props)=>({
      history: history.concat([{
        squares: squares,
      }]),
      blackIsNext: !state.blackIsNext,
      currentPosition: i,
      location:location
    }))
    // 未深刻理解，所以只能使用啥办法，异步让它排队走，以确保取到正确的值
    setTimeout(() =>{
      this.calculateWinner(x,y,squares,i) // 落子后判断一次胜负
    }, 0)
  }

  // 判断胜负
  calculateWinner(x, y, squares,i) {
    //落下子后需要进行统计
      for(let k=0; k<this.props.count; k++) {
        if(this.props.allwin[x][y][k]){//某种赢的某子true
          const blackWin = this.state.blackWin.slice()
          const whiteWin = this.state.whiteWin.slice()
          if(squares[i]=== 1) {
            blackWin[k]++       //黑棋离胜利又进一步
            whiteWin[k] = 999  //该种赢法计算机没有机会了，其实大于5就行
          } else {
            blackWin[k] = 999  
            whiteWin[k]++      
          }
          this.setState((state) => ({
            blackWin:blackWin  
          }))
          this.setState((state) => ({
            whiteWin: whiteWin 
          }))
          // console.log('blackWin',this.state.blackWin[k]);
          if(this.state.blackWin[k] === 5){ //如果达到5就赢了
            this.setState(()=>({
              over: true
            }))
            window.alert("厉害，黑棋胜！！")
          }
          if(this.state.whiteWin[k] === 5){ //如果达到5就赢了
            this.setState(()=>({
              over: true
            }))
            window.alert("你也太菜了吧，都干不过电脑！！")
          }
        }
      }
  }
  // 简易AI算法
  // 判断胜利只是简单的对赢法进行计数，AI需要权来判断需要走哪一步
  // 这是的方式是为所有赢法打分，自己怎么赢，不让对方赢，权重方面自己赢的权重略高于不让对方赢
  async computerAI () {
    let max = 0
    let u=0,v=0;
    //定义两个数组，用于存放每个点的分值
    // let myScore = Array(this.props.size).fill(Array(this.props.size).fill(0))
    // let computerScore = Array(this.props.size).fill(Array(this.props.size).fill(0))
    var myScore = [] ;//定义两个数组，用于存放每个点的分值
    var computerScore = [] ;
    for(let i=0; i<this.props.size; i++){
      myScore[i] = [] ;
      computerScore[i] = [] ;
      for(let j=0; j<this.props.size; j++){
          myScore[i][j] = 0 ;
          computerScore[i][j] = 0;
      }
    }
    const history = this.state.history
    const current = history[history.length-1];
    const squares = current.squares.slice();
    
    //为所有赢法打分
    for(let i=0; i<15; i++){
      for(let j=0; j<15; j++){
          if(!squares[i*15+j]){ //该点可下棋
              for(let k=0; k<this.props.count; k++){//遍历所有赢法
                  if(this.props.allwin[i][j][k]){ //这种赢法落子
                      if(this.state.blackWin[k] === 1){//黑方，有1个子
                          myScore[i][j] += 200 ;
                      }else if(this.state.blackWin[k] === 2){
                          myScore[i][j] += 400 ;
                      }else if(this.state.blackWin[k] === 3){
                          myScore[i][j] += 2000 ;
                      }else if(this.state.blackWin[k] === 4){
                          myScore[i][j] += 10000 ;
                      }
                      if(this.state.whiteWin[k] === 1){//白方，有1个子
                          computerScore[i][j] += 220 ;
                      }else if(this.state.whiteWin[k] === 2){
                          computerScore[i][j] += 420 ;
                      }else if(this.state.whiteWin[k] === 3){
                          computerScore[i][j] += 2200 ;
                      }else if(this.state.whiteWin[k] === 4){
                          computerScore[i][j] += 20000 ;
                      }
                  }
              }
              //下面判断计算机落子的最佳处
              if(myScore[i][j] > max ){//人在某步的权值更高的时候
                  max = myScore[i][j] ;
                  u = i ;
                  v = j ;
              }else if(myScore[i][j] === max){//如果权值是最大了
                  if(computerScore[i][j] > computerScore[u][v]){//而i,j点的权值比在u,v点的更大时
                      u = i ;
                      v = j ;
                  }
              }
              if(computerScore[i][j] > max ){//人在某步的权值更高的时候
                  max = computerScore[i][j] ;
                  u = i ;
                  v = j ;
              }else if(computerScore[i][j] === max){//如果权值是最大了
                  if(myScore[i][j] > myScore[u][v]){//而计算机在此处落子更有用
                      u = i ;
                      v = j ;
                  }
              }
          }
      }
    }
    // console.log('这时的myScore',myScore);
    // console.log('这时的UV：',u,v,max);
    setTimeout(() => {
      const position = coordinate.goX[v] + coordinate.goY[u]
      this.setBang(position,u*15+v,u,v)
    }, Math.floor(Math.random()*500)+500); // 这里写了个随机数，假装是个要思考的AI
  }
  render() {
    const history = this.state.history;
    const current = history[history.length - 1];
    const pos = this.state.location
    return (
      <div className="Gobang">
        <h2>{this.state.over?'游戏结束':(this.state.blackIsNext?"本轮落子：黑方":"本轮落子：白方")}</h2>
        <div className="gb_container">
          <Checkerboard 
            squares={current.squares}
            onClick={this.dealClick}
            blackIsNext ={this.state.blackIsNext}
            over={this.state.over}
            currentPosition = {this.state.currentPosition}
          />
        </div>
        <div className="systemDialog">
          <Message 
             blackIsNext = {this.state.blackIsNext}
             postion = {pos}
             over={this.state.over}
          />
          <Chat 
            role={this.state.role}
          />
        </div>
      </div>
    );
  }
}

export default Gobang;
